/*
 * Copyright (c) 2011 Samuel Ventura All Rights Reserved
 */
package dev2net;

import gnu.io.CommPort;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;

/**
 *
 * @author samuel
 */
public class Util {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss SSS ");
    
    private static Queue out;
    
    public static class Msg {
        public String str;
        public String typ;

        public Msg(String str, String typ) {
            this.str = str;
            this.typ = typ;
        }
    }
    
    public synchronized static void init() {
        if (out==null) out = new LinkedList();
    }
    
    public synchronized static Msg peek() {
        if (out==null) return null;
        return (Msg)out.poll();
    }
    
    public synchronized static void out(String s) {
        s = sdf.format(new Date()) + Thread.currentThread().getName() + ": " + s;
        System.out.println(s);
        if (out != null) out.add(new Msg(s,"out"));
    }
    
    public synchronized static void err(String s) {
        s = sdf.format(new Date()) + Thread.currentThread().getName() + ": " + s;
        System.err.println(s);
        if (out != null) out.add(new Msg(s,"err"));
    }
    
    public static void close(ClosableThread thread) {
        if (thread!=null) thread.close();
    }
    
    public static void close(ServerSocket socket) {
        try {
            if (socket!=null && !socket.isClosed()) socket.close();
        } catch (IOException ex) {
            out(ex.getMessage());
        }
    }

    public static void close(Socket socket) {
        try {
            if (socket!=null && !socket.isClosed()) socket.close();
        } catch (IOException ex) {
            out(ex.getMessage());
        }
    }

    public static void close(CommPort commPort) {
        try {
            if (commPort!=null) commPort.close();
        } catch (Exception ex) {
            out(ex.getMessage());
        }
    }
}
